#!/usr/bin/env python3

import os

from openpyxl import load_workbook
from openpyxl.styles import Font, PatternFill

import argparse
import sys


sys.path.append("../lib")
from inner_util import prepare_dir, get_files


DEFAULT_FONT = Font(bold=False, color="000000", size=9)
MODIFY_FONT = Font(bold=True, color="FF0000", size=9)

FILL_YELLOW = PatternFill(start_color="FFFF00", end_color="FFFF00", fill_type="solid")
FILL_WHITE = PatternFill(start_color="FFFFff", end_color="FFFFff", fill_type="solid")

TARGET_DIR = "dist"


def build_font(size):
    default = Font(bold=False, color="000000", size=size)
    modify = Font(bold=True, color="FF0000", size=size)

    return {
        "default": default,
        "modify": modify,
    }


def parse_args():
    parser = argparse.ArgumentParser(description="汇总表格")
    parser.add_argument("--start-row", help="起始行")
    parser.add_argument("--data", help="数据文件")
    parser.add_argument("template", help="文件路径")
    return parser.parse_args()


def try_file_path(file_path):
    """测试是否存在文件，如果存在，返回带括号的文件名"""
    tmp_path = file_path
    (root, ext) = os.path.splitext(file_path)
    i = 1
    while os.path.exists(tmp_path):
        tmp_path = f"{root}({i}){ext}"
        i += 1

    return tmp_path


def read_from_xlsx(src_file, sheet_index=0, row_offset=0, max_col=0):
    """从 xlsx 文件读取数据，全是0索引"""
    wb = load_workbook(src_file, data_only=True)
    ws = wb.worksheets[sheet_index]
    data = list(ws.values)[row_offset:]
    res = []
    for row in data:
        sub_row = row if max_col == 0 else row[:max_col]
        res.append(sub_row)
    return res


class CollectWorkbook:
    def __init__(self, args):
        self.args = args
        self.data_rows = read_from_xlsx(args.template)

        self.wb = load_workbook(args.template, data_only=True)

    def merge_files(self, other_file):
        ws = self.wb.active
        print("Start row", self.args.start_row)
        other_data_rows = read_from_xlsx(other_file, 0, int(self.args.start_row))
        for row in other_data_rows:
            ws.append(row)

    def save_as(self, target_path):
        self.wb.save(try_file_path(target_path))


def usage():
    print("""
python3 collect.py --start-row=3 --data=<data_dir> template.xlsx
""")


def main():
    usage()

    prepare_dir(TARGET_DIR, False)

    args = parse_args()

    print("Args", args)

    left = CollectWorkbook(args)

    right_files = get_files(args.data, ".xlsx", True)

    for f in right_files:
        print(f"合并 {f} 到原表")
        left.merge_files(f)

    left.save_as(f"合并-{args.template}.xlsx")
    print("Done")


if __name__ == "__main__":
    main()
